package com.yxinsur.imc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.ImcIns;
import com.yxinsur.imc.business.domain.ImcRepoIns;
import com.yxinsur.imc.business.domain.ImcSupplier;
import com.yxinsur.imc.business.enums.IsDeletedEnum;
import com.yxinsur.imc.business.form.InsFactorForm;
import com.yxinsur.imc.business.form.InsSearchForm;
import com.yxinsur.imc.business.mapper.ImcInsMapper;
import com.yxinsur.imc.business.mapper.ImcRepoInsMapper;
import com.yxinsur.imc.business.mapper.ImcSupplierMapper;
import com.yxinsur.imc.business.service.IImcInsService;
import com.yxinsur.imc.business.vo.InsRateVo;
import com.yxinsur.imc.business.vo.InsVo;
import com.yxinsur.imc.business.vo.RepoInsExportVo;
import com.yxinsur.imc.business.vo.select.SelectIns;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.utils.DateUtils;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.validator.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的保险产品库(险种)Service业务层处理
 *
 * @author imc
 * @date 2021-03-26
 */
@Service
public class ImcInsServiceImpl extends ServiceImpl<ImcInsMapper, ImcIns> implements IImcInsService
{
    private static final Logger logger = LoggerFactory.getLogger(ImcInsServiceImpl.class);

    @Autowired
    private ImcInsMapper imcInsMapper;
    @Autowired
    private ImcRepoInsMapper imcRepoInsMapper;
    @Autowired
    private ImcSupplierMapper imcSupplierMapper;
    @Autowired
    private ImcInsRateServiceImpl imcInsRateService;

    /**
     * 查询我的保险产品库(险种)
     *
     * @param id 我的保险产品库(险种)ID
     * @return 我的保险产品库(险种)
     */
    @Override
    public ImcIns selectImcInsById(String id)
    {
        return null;
    }

    /**
     * 查询我的保险产品库(险种)列表
     *
     * @param insForm 我的保险产品库(险种)
     * @return 我的保险产品库(险种)
     */
    @Override
    public List<InsVo> selectImcInsList(InsSearchForm insForm)
    {
        logger.info("我的保险产品列表查询，条件：{}",insForm.toString());
        insForm.setTenantId(SecurityUtils.getTenantId());
        return imcInsMapper.selectImcInsList(insForm);
    }

    /**
     * 新增我的保险产品库(险种)
     *
     * @param repoInsIds 我的保险产品库(险种)
     * @return 结果
     */
    @Override
    public int insertImcIns(Long[] repoInsIds)
    {
        logger.info("我的保险产品新增操作：{}",repoInsIds);
        for (Long repoInsId:repoInsIds) {
            ImcIns ins = new ImcIns();
            ins.setRepoInsId(repoInsId);
            ins.setCreateTime(DateUtils.getNowDate());
            ins.setCreateId(SecurityUtils.getUsername());
            ins.setIsDeleted(IsDeletedEnum.N.getCode());
            ins.setTenantId(SecurityUtils.getTenantId());
            this.imcInsMapper.insert(ins);
        }

        return repoInsIds.length;
    }

    /**
     * 更新我的险种扩展字段名称
     *
     * @param factorForm 险种扩展字段
     * @return 结果
     */
    @Override
    public int updateImcInsFactors(InsFactorForm factorForm) {
        Assert.isNull(factorForm.getRepoInsId(),"传参有误，险种ID(repoInsId)不能为空");
        QueryWrapper<ImcIns> insQueryWrapper = new QueryWrapper<>();
        insQueryWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        insQueryWrapper.eq("tenant_id",SecurityUtils.getTenantId());
        insQueryWrapper.eq("repo_ins_id",factorForm.getRepoInsId());
        List<ImcIns> insList = this.imcInsMapper.selectList(insQueryWrapper);
        if(insList.size() == 1){
            ImcIns ins = insList.get(0);
            ins.setFactor1Title(factorForm.getFactor1Title());
            ins.setFactor2Title(factorForm.getFactor2Title());
            ins.setFactor3Title(factorForm.getFactor3Title());
            ins.setUpdateId(SecurityUtils.getUsername());
            ins.setUpdateTime(DateUtils.getNowDate());
            return this.imcInsMapper.updateById(ins);
        }else if(insList.size() > 1){
            throw new BusinessException("险种ID配置有误，匹配到多个");
        }else{
            throw new BusinessException("险种ID配置有误，未查询到数据");
        }
    }

    /**
     * 批量删除我的保险产品库(险种)
     *
     * @param ids 需要删除的我的保险产品库(险种)ID
     * @return 结果
     */
    @Override
    public int deleteImcInsByIds(Long[] ids)
    {
        logger.info("我的保险产品删除操作：{}",ids);
        int count = 0;
        for(Long id:ids){
            ImcIns ins = this.imcInsMapper.selectById(id);
            ins.setIsDeleted(ins.getId());
            ins.setUpdateId(SecurityUtils.getUsername());
            ins.setUpdateTime(DateUtils.getNowDate());
            count += this.imcInsMapper.updateById(ins);
        }
        return count;
    }

    /**
     * 下拉列表数据获取
     *
     * @param repoSupplierId 保险公司id
     * @return 结果
     */
    @Override
    public List<SelectIns> selectDataList(Long repoSupplierId) {
        QueryWrapper<ImcSupplier> supplierQueryWrapper = new QueryWrapper<>();
        supplierQueryWrapper.eq("repo_supplier_id",repoSupplierId);
        supplierQueryWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        supplierQueryWrapper.eq("tenant_id",SecurityUtils.getTenantId());
        List<ImcSupplier> suppliers = this.imcSupplierMapper.selectList(supplierQueryWrapper);
        if(suppliers.size() == 0){
            throw new BusinessException("您暂无该供应商的数据及险种权限");
        }
        QueryWrapper<ImcIns> insWrapper = new QueryWrapper<>();
        insWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        insWrapper.eq("tenant_id",SecurityUtils.getTenantId());
        List<ImcIns> inses = this.imcInsMapper.selectList(insWrapper);
        List<Long> repoIds = new ArrayList<>();
        repoIds.add(-1L);
        inses.stream().forEach(i ->{
            repoIds.add(i.getRepoInsId());
        });
        //查询权限配置的产品列表
        QueryWrapper<ImcRepoIns> repoInsWrapper = new QueryWrapper<>();
        repoInsWrapper.in("id",repoIds);
        repoInsWrapper.eq("repo_supplier_id",repoSupplierId);
        repoInsWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        List<ImcRepoIns> repoInsList = this.imcRepoInsMapper.selectList(repoInsWrapper);
        List<SelectIns> selectList = new ArrayList<>();
        repoInsList.stream().forEach(i ->{
            SelectIns selectIns = new SelectIns();
            BeanUtils.copyProperties(i,selectIns);
            selectList.add(selectIns);
        });
        return selectList;
    }

    /**
     * 费率配置导出险种详情信息
     * @param insForm
     * @return
     */
    @Override
    public List<RepoInsExportVo> exportInsList(InsSearchForm insForm) {
        List<InsVo> insList = this.selectImcInsList(insForm);

        ArrayList<RepoInsExportVo> exportVos = new ArrayList<>();
        for (InsVo insVo : insList) {
            String repoInsId = insVo.getRepoInsId();
            List<InsRateVo> rateVos = imcInsRateService.selectImcInsRateList(Long.parseLong(repoInsId));
            for (InsRateVo rateVo : rateVos) {
                RepoInsExportVo repoInsExportVo = new RepoInsExportVo();
                BeanUtils.copyProperties(rateVo,repoInsExportVo);
                BeanUtils.copyProperties(insVo,repoInsExportVo);
                repoInsExportVo.setId(Long.parseLong(rateVo.getId()));
                exportVos.add(repoInsExportVo);
            }
        }
        return exportVos;
    }

    @Override
    public List<RepoInsExportVo> exportInsListByRepoInsId(Long repoInsId) {
        InsSearchForm insSearchForm = new InsSearchForm();
        insSearchForm.setTenantId(SecurityUtils.getTenantId());
        insSearchForm.setRepoInsId(repoInsId);
        exportInsList(insSearchForm);
        return exportInsList(insSearchForm);
    }
}
